﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using BlogApp.Data.Models;
using BlogApp.Data.Service;
using BlogApp.WP8.Resources;
using BlogApp.WP8.Utils;
using GalaSoft.MvvmLight.Command;

namespace BlogApp.WP8.ViewModel
{
    public class CategoryViewModel : DataViewModel
    {
        Dictionary<Category, int> _categoryPageIndexs = new Dictionary<Category, int>();
        Dictionary<Category, PostResult> _loadedCategories = new Dictionary<Category, PostResult>();


        private Category _selectedCategory;
        public Category SelectedCategory
        {
            get { return _selectedCategory; }
            set
            {
                _selectedCategory = value;
                RaisePropertyChanged("SelectedCategory");
            }
        }


        private PostResult _postsForCategory;
        public PostResult PostsForCategory
        {
            get { return _postsForCategory; }
            set { _postsForCategory = value; RaisePropertyChanged("PostsForCategory"); }
        }

        public RelayCommand<Category> LoadCategoryCommand { get; private set; }
        public NavigateCommand NavigateCommand { get; private set; }
        public RelayCommand LoadMoreItems { get; private set; }


        public CategoryViewModel()
        {
            LoadCategoryCommand = new RelayCommand<Category>(loadCategory);
            LoadMoreItems = new RelayCommand(loadMoreItems);

            NavigateCommand = new NavigateCommand();
        }

        private async Task loadPostsForSelectedCategory()
        {
            if (!DataService.Instance.IsOffline)
            {
                var result = await DataService.Instance.GetPostsBySlugAsync(_selectedCategory);

                if (result != null)
                {
                    PostsForCategory = result;
                }
            }

        }

        private async void loadCategory(Category category)
        {
            NavigateCommand.Execute("/View/CategoryPage.xaml");


            if (category.Title == AppResources.AppBarMenuItemSaveOfflineText)
            {
                List<Post> offline = await DataService.Instance.LoadOfflinePosts();
                _postsForCategory = new PostResult()
                {
                    Posts = new ObservableCollection<Post>(offline),
                    Count = 0,
                    CountTotal = 0,
                    Pages = 0
                };

                // ToDo: Fix that!
                NavigateCommand.Execute("/View/CategoryPage.xaml");
                return;
            }


            if (!DataService.Instance.IsOffline)
            {
                try
                {
                    _selectedCategory = category;

                    IsLoading = true;

                    // restore already loaded post for category
                    if (_loadedCategories.Any(e => e.Key == category))
                    {
                        _postsForCategory = _loadedCategories.FirstOrDefault(e => e.Key == category).Value;

                        //// store available count of pages
                        //_categoryPageIndexs.CreateOrUpdateElement(category, 1);
                    }
                    else
                    {
                        await loadPostsForSelectedCategory();
                    }

                    if (_postsForCategory == null)
                    {
                        MessageBox.Show(AppResources.MessageBoxErrorConnection);
                    }

                    // store items
                    _loadedCategories.CreateOrUpdateElement(_selectedCategory, _postsForCategory);

                }
                catch (Exception)
                {
                    
                }

                //NavigateCommand.Execute("/View/CategoryPage.xaml");

                IsLoading = false;
            }
            else
            {
                MessageBox.Show(AppResources.MessageBoxErrorConnection);
            }
        }

        private async void loadMoreItems()
        {
            if (!DataService.Instance.IsOffline)
            {
                IsLoading = true;
                try
                {
                    int pageIndex = 2; // set to 2 as it wont meet the condition to increment the pageIndex for the first run

                    if (_categoryPageIndexs.ContainsKey(_selectedCategory))
                    {
                        pageIndex = _categoryPageIndexs.FirstOrDefault(e => e.Key == _selectedCategory).Value;
                        pageIndex++;
                    }

                    _categoryPageIndexs.CreateOrUpdateElement(_selectedCategory, pageIndex);

                    if (pageIndex <= _postsForCategory.Pages)
                    {
                        var moreItems = await DataService.Instance.GetPostsBySlugAsync(_selectedCategory, pageIndex);
                        _postsForCategory.Posts.AddRange(moreItems.Posts);

                        // store items
                        _loadedCategories.CreateOrUpdateElement(_selectedCategory, _postsForCategory);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                IsLoading = false;
            }
        }
    }
}